package mx.netbrain.dao.impl;

import java.util.List;

import mx.netbrain.dao.UserDao;
import mx.netbrain.model.User;
import mx.netbrain.util.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

public class UserDaoImpl implements UserDao {

	private static final Logger logger = Logger.getLogger(UserDaoImpl.class);

	@Override
	public User findForUser(String username, String password) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		String sql = "select u from User u where username=:user and password=:pass";
		Query query = session.createQuery(sql);
		query.setString("user", username);
		query.setString("pass", password);
		if ((User) query.uniqueResult() != null) {
			return (User) query.uniqueResult();
		} else {
			logger.error("No se encontro ningun registro con el usuario: "
					+ username);
			return (User) query.uniqueResult();
		}
	}

	@Override
	public void save(User user) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.persist(user);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Save: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public void update(User user) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(user);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Update: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public void delete(User user) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(user);
			session.beginTransaction().commit();
			session.close();
		} catch (Exception e) {
			logger.error("Delete: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public User findById(Long id) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return (User) session.load(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> listAll() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return session
				.createQuery("from User as user where user.status.id = 1")
				.list();
	}

}
